package com.colorlight.cloud.gateway.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Demon
 * @date 26/10/2023 下午3:17
 */
@Slf4j
public class FileUtils {
  /**
   * @param file 源文件
   * @return 源文件 de5
   */
  public static String calcFileMd5(MultipartFile file) {
    try {
      return calcMD5(file.getInputStream());
    } catch (IOException e) {
      log.error("", e);
      return "";
    }
  }

  /**
   * @param stream 文件流
   * @return 源文件 de5
   */
  public static String calcMD5(InputStream stream) {
    try {
      MessageDigest digest = MessageDigest.getInstance("MD5");
      byte[] buf = new byte[8192];
      int len;
      while ((len = stream.read(buf)) > 0) {
        digest.update(buf, 0, len);
      }
      return toHexString(digest.digest());
    } catch (IOException | NoSuchAlgorithmException e) {
      log.error("", e);
      return "";
    }
  }

  /**
   * @param data byte数组
   * @return MD5
   */
  public static String toHexString(byte[] data) {
    char[] hexCode = "0123456789ABCDEF".toCharArray();
    StringBuilder r = new StringBuilder(data.length * 2);
    for (byte b : data) {
      r.append(hexCode[(b >> 4) & 0xF]);
      r.append(hexCode[(b & 0xF)]);
    }
    return r.toString();
  }

  /**
   * @param path 文件路径
   * @param file 源文件
   * @return 上传结果
   */
  @Deprecated
  public static boolean writeFileToPath(String path, MultipartFile file) {
    try {
      File distFile = new File(path);
      if (distFile.exists()) {
        return true;
      }

      if (!distFile.getParentFile().exists()) {
        distFile.getParentFile().mkdirs();
      }

      file.transferTo(distFile);
      return true;
    } catch (IOException e) {
      log.error("", e);
      return false;
    }
  }

  /**
   * @param inputStream 文件流
   * @param filepath 目标路径+文件名
   */
  public static void createFile(InputStream inputStream, String filepath) throws IOException {
    File file = new File(filepath);
    if (!file.exists()) {
      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }
      file.createNewFile();
    }
    OutputStream outputStream = java.nio.file.Files.newOutputStream(Paths.get(filepath));
    FileCopyUtils.copy(inputStream, outputStream);
  }

  /**
   * 获取文件名后缀
   *
   * @param fileName 文件名
   * @return 后缀
   */
  public static String getFileNameSuffix(String fileName) {
    String fileExtension = FilenameUtils.getExtension(fileName);
    return fileExtension != null ? fileExtension : "";
  }
}
